﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ScFramework.Core;
using UnityEngine.UI;


public partial class WorkshopLogic : LogicModuleBase<InputManager,SpriteManager>, ICombineSubUI
{
    #region 更改方格大小及数量会更改的参数
    const int RAW = 7;
    const int COL = 7;
    const int BLOCKSIZE = 80;
    const int BIASX = -240;
    const int BIASY = -250;
    #endregion

    static GameObject workshop;
    static GameObject withMouse;
    static List<MeshEntityData> currentEntity = new List<MeshEntityData>();
    static List<MeshEntityData> currentEntityInWorkShop = new List<MeshEntityData>();

    //static MeshEntityData currentDrag = null;   

    static Grid workshopGrid;

    static DragManager dragManager;
    static FlipRotateManager flipRotateManager;
    static SpriteManager spmgr;

    public override void OnInit(object args)
    {
        base.OnInit(args);
        spmgr = SysModule1;
    }

    /// <summary>
    /// 拼装台的一个方格 包含自己的整数坐标 是否被占用 以及Block对象
    /// </summary>
    public class Block
    {
        public GameObject singleBlock;
        public int x;       //(unsafe) coordinate in array
        public int y;
        public bool isOccupied;
        public int occupyID;
        public Block(int xx, int yy, GameObject block)
        {
            isOccupied = false;
            x = xx;
            y = yy;
            singleBlock = block;
            singleBlock.transform.Find("Text").transform.localScale = new Vector3(1, 1, 1);
            singleBlock.transform.Find("Text").GetComponent<Text>().text = x + " , " + y;
            singleBlock.GetComponent<MyButton>().section = 1;
            singleBlock.GetComponent<MyButton>().posX = x;
            singleBlock.GetComponent<MyButton>().posY = y;
        }
    }

    /// <summary>
    /// 整个拼装台的方格集合 包含二维List 
    /// </summary>
    public class Grid
    {
        public static List<List<Block>> GridList;                        
        public Grid()
        {
            GridList = new List<List<Block>>(RAW);

            for (int i = 0; i < RAW; i++)
            {
                List<Block> oneRawList = new List<Block>(COL);          //oneRawList不重新分配会覆盖之前的行列表
                for (int j = 0; j < COL; j++)
                {
                    GameObject tmp = ResourceManager.Instance.Instantiate("Prefab/UI/CombineUISub/SubSub/SingleBlock",workshop.transform);
                    tmp.transform.localScale = new Vector3(1, 1, 1);
                    Vector3 tmpPosition;
                    tmpPosition.x = BIASX + (i * BLOCKSIZE);
                    tmpPosition.y = BIASY + (j * BLOCKSIZE);
                    tmpPosition.z = 0f;                                 
                    tmp.transform.localPosition = tmpPosition;
                    oneRawList.Add(new Block(i, j, tmp));                  
                }
                GridList.Add(oneRawList);
            }
        }


        public static void DeleteImg(int x, int y, MeshEntityData toDelete, string nameToDel)
        {
            List<Vector3Int> subList = new List<Vector3Int>();
            subList = FlipRotateManager.ListTransform(toDelete);
            foreach(var e in subList)
            {
                if(DragManager.IsDeltaXYOverFlow(x + e.x, y + e.y))//||(Grid.GridList[x + e.x][y + e.y].isOccupied)&& Grid.GridList[x + e.x][y + e.y].occupyID == toDelete.ID
                {
                    continue;
                }
                if(Grid.GridList[x + e.x][y + e.y].singleBlock.transform.Find(nameToDel) != null)
                {
                    Grid.GridList[x + e.x][y + e.y].singleBlock.transform.Find(nameToDel).gameObject.SetActive(false);
                }
            }
        }
        public static void ShowMultiDraggingSprite(int x, int y, MeshEntityData toShow, List<Vector3Int> listBeforeTrans, string nameOfSprite, string color)
        {
            /*string path = "Sprite/EntitySprite/";
            path += toShow.Body.SpriteName;
            path = path.Substring(0, path.Length - 2);
            Sprite[] allSubarr = Resources.LoadAll<Sprite>(path);
            List<Sprite> allSubList = new List<Sprite>(allSubarr);
            if (allSubList.Count == 0)
            {
                Debug.LogError("With 0 Child");
            }*/
            foreach (var s in listBeforeTrans)
            {
                string totalName = toShow.Body.SpriteName;
                totalName += (s.x + 6).ToString() + (s.y + 6).ToString();

                Sprite spritetoShow = spmgr.GetSpriteBench(totalName);

                Vector3Int transedV = FlipRotateManager.VectorTransform(toShow, new Vector3Int(s.x, s.y, 0));

                if (DragManager.IsDeltaXYOverFlow(x + transedV.x, y + transedV.y))
                {
                    continue;
                }
                GameObject Img = GridList[x + transedV.x][y + transedV.y].singleBlock.transform.Find(nameOfSprite).gameObject;

                if (Img.activeSelf == true)
                {
                    continue;
                }
                Img.GetComponent<Image>().sprite = spritetoShow;
                switch(color)
                {
                    case "WHITE":
                        {
                            //Img.GetComponent<Image>().color = Color.blue;
                            break;
                        }
                    case "RED":
                        {
                            //Img.GetComponent<Image>().color = Color.red;
                            break;
                        }
                }

                Img.GetComponent<Transform>().localPosition = new Vector3Int(0, 0, 0);
                Img.GetComponent<Transform>().localScale = new Vector3Int(1, 1, 1);
                FlipRotateManager.SpriteTransform(toShow, Img, false);
                Img.SetActive(true);
            }
        }
        public static void RefreshWorkshopGrid()          //它来订阅刷新
        {
            //Debug.LogError("REFRESH!!!");
            //DebugDisPlayAll();

            for (int i = 0; i < RAW; i++)
                for (int j = 0; j < COL; j++)
                {
                    if (Grid.GridList[i][j].singleBlock.transform.Find("InGrid") != null)
                    {
                        Grid.GridList[i][j].singleBlock.transform.Find("InGrid").gameObject.SetActive(false);
                    }
                }
            foreach (var e in currentEntityInWorkShop)
            {
                List<Vector3Int> subListOri = new List<Vector3Int>();
                foreach(var s in e.Colliders)
                {
                    subListOri.AddRange(s.LocalMeshPos);
                }
                Grid.ShowMultiDraggingSprite(e.Body.MeshPos.x, e.Body.MeshPos.y, e, subListOri, "InGrid", "WHITE");       
            }
        }
        public static void DebugDisPlayAll()
        {
            Debug.Log("-------------------START-----------------------");
            foreach(var x in currentEntityInWorkShop)
            {
                Debug.Log(x.Name);
            }
            Debug.Log("-------------------END-----------------------");

        }
    }

    

    /// <summary>
    /// 订阅DragManager 在指定方格显示物体
    /// </summary>
    /// <param name="id"></param>
    /// <param name="x"></param>
    /// <param name="y"></param>
    public class DraggedEntityShow
    {
       // public static MeshEntityData toShow = currentEntity.Find(xx => xx.ID == id);

        public static void ShowEntityWithMouse(Vector3 mousePos)
        {
            withMouse.transform.position = mousePos;
        }
        public static void ShowDraggingEntity(int id, int x, int y, int oldX, int oldY)
        {

            Debug.Log("THE " + WorkshopLogic.currentEntity[id-1].Name + " TRYING show in " + x + " , " + y);

            List<Vector3Int> SubBoxsLocalPos = new List<Vector3Int>();

            foreach (var s in dragManager.entityDragging.Colliders)
            {
                SubBoxsLocalPos.AddRange(s.LocalMeshPos);
            }


            if (DragManager.IsDeltaXYOverFlow(x, y, dragManager.entityDragging))
            {
                Debug.Log("FAILED FOR 出界");
                DeleteOld(oldX, oldY);
                Grid.ShowMultiDraggingSprite(x, y, dragManager.entityDragging, SubBoxsLocalPos, "Predict", "RED");
                return;
            }

            if (DragManager.IsOccupied(x, y, dragManager.entityDragging))
            {
                Debug.Log("FAILED FOR 方格被占用");
                DeleteOld(oldX, oldY);
                Grid.ShowMultiDraggingSprite(x, y, dragManager.entityDragging, SubBoxsLocalPos, "Predict", "RED");
                return;
            }

            DeleteOld(oldX, oldY);

            Grid.ShowMultiDraggingSprite(x, y, dragManager.entityDragging, SubBoxsLocalPos, "Predict", "WHITE");

            Debug.Log("SUCCEED");
        }
        public static void DeleteOld(int oldX, int oldY)
        {
            //if (!DragManager.IsDeltaXYOverFlow(oldX, oldY, dragManager.entityDragging) && !DragManager.IsOccupied(oldX, oldY, dragManager.entityDragging))
            //{
                Grid.DeleteImg(oldX, oldY, dragManager.entityDragging,"Predict");
            //}
        }
        public static void DeleteEntitySprite(int id, int x, int y, string toDel)
        {
            Grid.DeleteImg(x, y, dragManager.entityDragging, toDel);
        }
    }

    public void InitGameobject(List<GameObject> obj)
    {
        workshop = obj.Find(s => s.name == "Workshop"); 
        withMouse = workshop.transform.parent.Find("DiagImage").gameObject;
        Texture2D tmpPix = Resources.Load("Sprite/EntitySprite/NoImg") as Texture2D;
        Sprite tmpSprite = Sprite.Create(tmpPix, new Rect(0, 0, withMouse.GetComponent<RectTransform>().rect.width, withMouse.GetComponent<RectTransform>().rect.height), new Vector2(0.5f, 0.5f));
        withMouse.GetComponent<Image>().sprite = tmpSprite;
        workshopGrid = new Grid();

        //ButtonManager实例化
        ButtonManagerInit();

        //事件实例化
        dragManager = new DragManager();   //实例化一个事件发布类
        dragManager.OnDragStop += new DragManager.DragEndHandler(DispatchAlter);
        dragManager.OnPredictChange += new DragManager.PredictChangeHandler(DraggedEntityShow.ShowDraggingEntity);
        dragManager.OnWorkshopRefresh += new DragManager.WorkshopRefreshHandler(Grid.RefreshWorkshopGrid);
        dragManager.OnDragStart += new DragManager.DragStartHandler(dragManager.DragVarInit);
        flipRotateManager = new FlipRotateManager();

    }
    public override void OnEnable()
    {

        base.OnEnable();
        Grid.RefreshWorkshopGrid();
        workshop.SetActive(true);
    }
    public override void OnDisable()
    {
        base.OnDisable();
        workshop.SetActive(false);
        //workshop.SetActive(true);
    }

    /// <summary>
    /// 每帧 
    /// </summary>
    public override void FixedUpdate()      //基于事件 主函数甚至什么都不知道
    {
        base.FixedUpdate();
        if(DragManager.inDrag)
        {
            dragManager.PredictBlockSearch(SysModule.MousePosition);
            DraggedEntityShow.ShowEntityWithMouse(SysModule.MousePosition);
            if (Input.GetMouseButtonUp(0))
            {
                Dispatch(CombineUIEvent.DragObject, -1);
            }
        }
    }

    /// <summary>
    /// 刷新
    /// </summary>
    [RegisterEvent(CombineUIEvent.Receive_Data)]
    void Refresh(List<MeshEntityData> datas)
    {
        currentEntity =new List<MeshEntityData>(datas);
        currentEntityInWorkShop = new List<MeshEntityData>();
        foreach(var e in currentEntity)
        {
            if(e.Body.PresentPos == 1)
            {
                currentEntityInWorkShop.Add(e);
            }
        }
        Grid.RefreshWorkshopGrid();
    }

    /// <summary>
    /// 触发翻转
    /// </summary>
    /// <param name="id"></param>
    [RegisterEvent( CombineUIEvent.FlipEntity)]
    void EntityFlip(ushort id)
    {
        if (id <= 0)
        {
            Debug.LogWarning("选中处不存在实体");
            return;
        }
        flipRotateManager.FlipTrigged(id);

    }

    /// <summary>
    /// 触发旋转
    /// </summary>
    /// <param name="id"></param>
    [RegisterEvent(CombineUIEvent.SpinEntity)]
    void EntityRotate(ushort id)
    {
        if (id <= 0)
        {
            Debug.LogWarning("选中处不存在实体");
            return;
        }
        flipRotateManager.RotateTrigged(id);

    }

    /// <summary>
    /// 是否有拖拽，拖拽id为
    /// </summary>
    [RegisterEvent(CombineUIEvent.DragObject)]
    void EntityDrag(int id)
    {
        if(id>0)
        {
            if(DragManager.inDrag == false)
            {
                dragManager.DragStart(id);
            }
        }
        else
        {
            if (DragManager.inDrag) // && !DragManager.IsDeltaXYOverFlow(dragManager.DeltaX, dragManager.DeltaY)
            {
                dragManager.DragStop(DragManager.DragID,dragManager.DeltaX,dragManager.DeltaY);
            }
        }
    }

}
